package com.li.shop.controller;

import com.li.shop.domain.*;
import com.li.shop.domain.Dictionary;
import com.li.shop.mapper.ProductMapper;
import com.li.shop.service.*;
import com.li.shop.utils.SearchProductGetResponse;
import com.li.shop.utils.SearchProductResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;


//李栋
@Controller
@RequestMapping("/product")
public class ProductController {

    //注入ProductService
    @Autowired
    private ProductService productService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private ShopCardService shopCardService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ProductDetailsService productDetailsService;
    @Autowired
    private ProductPicService productPicService;
    @Autowired
    private FootService footService;
    @Autowired ProductGetService productGetService;
    @Autowired
    ProductMapper productMapper;
    /**
     * 前端主页面的商品的展示：当项目启动的时候，前端展示商品页面。
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String show(Model model, HttpSession httpSession) {
        List<Product> product = productService.listAll();
        model.addAttribute("product", product);
        List<Dictionary> dict = dictionaryService.list();
        model.addAttribute("dictionary", dict);
        //拿到种类对应的商品种类
        List<Dictionary> d = dictionaryService.findAll();
        model.addAttribute("d", dict);
        //将用户的id放在session中
        String id = httpSession.getAttribute("id").toString();
        httpSession.setAttribute("id", id);
        return "before/home";
    }


    /**
     * 根据shopCard的id查出所有的商品名称
     * */
    @RequestMapping(value = "/showproduct", method = RequestMethod.GET)
    public String show(@RequestParam("did") String did, Model model, HttpSession session) {
        List<Product> product = productService.listAll();
        model.addAttribute("product", product);

        List<Dictionary> dict = dictionaryService.list();
        model.addAttribute("dictionary", dict);

        //拿到种类对应的商品种类
        List<Dictionary> d = dictionaryService.findAll();
        model.addAttribute("d", dict);

        //将用户的id放在session中
        String id = session.getAttribute("id").toString();
        session.setAttribute("id", id);
        /**
         * 方法一：关联查询查出所有的种类的产品类型
         * */
        /*
        List<Dictionary> d1=dictionaryService.findAll1();
        for (Dictionary list:d1){
            if( list.getProducts().isEmpty()){
                System.out.println( list.getName()+"该种类没有对应的商品种类");
            }
            else {
                System.out.println("种类为:" + list.getName() + "种类包含的信息为" + list.getProducts().get(0).getProductName());
            }
            model.addAttribute("list",list);
        }*/

        /**
         * 方法二：使用Mybatis 的productExample类型进行查询
         * */
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andPIdIsNotNull().andDIdEqualTo(did);
        List<Product> list = productService.selectByExample(productExample);
        model.addAttribute("list", list);
        return "before/loginsuccess";
    }


    /**
     * 进入商品详情页面，根据传入的商品id查询到详细内容(详情、图片)
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Model model, @RequestParam("id") String id,HttpSession session) {

        //根据p_id拿到该商品的所有信息
        Product product = productService.selectByPrimaryKey(id);
        ProductDetails productDetails=productDetailsService.find(id);
        ProductPic productPic=productPicService.find(id);

        model.addAttribute("product", product);
        model.addAttribute("product1",productDetails);
        model.addAttribute("productPic",productPic);

        String pname=product.getProductName();//tktk
        model.addAttribute("pname",product.getProductName());//tktk
        session.setAttribute("pname",product.getProductName());//tktk
        List<Product> list1=productService.findalllike(pname);//tktk根据相似商品推荐
        model.addAttribute("list1",list1);
        session.setAttribute("product",product);//添加
        model.addAttribute("pid",product.getpId());
        session.setAttribute("pid",product.getpId());//添加
        //留言模块
        List<Message> list = messageService.findAll(id);
        //System.out.println(list.get(0).getLiuYans().get(0).getLiucontent());
        User user=(User) session.getAttribute("session_user");
        //Product product2=(Product)session.getAttribute("product2") ;
        //user.getUpic();
        model.addAttribute("uId",user.getuId());
        model.addAttribute("upic",user.getUpic());
        model.addAttribute("userName",user.getUserName());
        model.addAttribute("list", list);
        //System.out.println(list.size());
        //System.out.println(list);

//        List<Message> list=productService.findAll();
//        model.addAttribute("list",list);
        String fuid=user.getuId();
//        Date date = new Date();
//        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        //System.out.println(dateFormat.format(date));
        Date date = new Date();
        Timestamp fdate = new Timestamp(date.getTime());


        Foot foot=new Foot();
        foot.setuId(fuid);
        foot.setpId(id);
        foot.setDate(fdate);
        int updated = footService.saveFoot(foot);

        return "/before/introduction";
    }
    @RequestMapping(value = "/detailrexiao", method = RequestMethod.GET)
    public String detailrexiao(Model model, @RequestParam("phname") String phname) {

        //根据p_id拿到该商品的所有信息
//        Product product = productService.selectByPrimaryKey(id);

        System.out.println("名字是"+phname);
        List<Product>productpId= productService.rexiao(phname);
        for(Product productpid:productpId)
        {
            productpid.getpId();
            ProductDetails productDetails=productDetailsService.find(productpid.getpId());
            ProductPic productPic=productPicService.find(productpid.getpId());
            model.addAttribute("product1",productDetails);
            model.addAttribute("productPic",productPic);
            List<Message> list = messageService.findAll(productpid.getpId());
            System.out.println(list.get(0).getLiuYans().get(0).getLiucontent());
            model.addAttribute("list", list);
        }


        ProductExample example=new ProductExample();
        example.createCriteria().andProductNameEqualTo(phname);
        List<Product>product= productMapper.selectByExample(example);

        model.addAttribute("product", product);


        //留言模块


        return "/before/introduction";
    }

    /**
     * 在购物车界面显根据当前session中的id 显示所有的商品
     */
    @RequestMapping(value = "/listall", method = RequestMethod.GET)
    public String list(Model model, HttpSession session) {
        //得到当前用户的id
        String id = session.getAttribute("id").toString();
        System.out.println("展示商品的时候uid为" + id);

        //根据u_id查出所有的p_id、pnum、p.*展示
        List<Shopcard> shopcards = shopCardService.searchgoods(id);
        System.out.println("shopcards的大小为" + shopcards.size());
        double sum = 0;
        int num = 0;
        int productnum = 0;
        for (int i = 0; i < shopcards.size(); i++) {
            sum += Integer.parseInt(shopcards.get(i).getPnum()) * shopcards.get(i).getProducts().get(0).getDazhe();
            num += Integer.parseInt(shopcards.get(i).getPnum());
            productnum += Integer.parseInt(shopcards.get(i).getPnum());
            System.out.println("当前购物车中的数量为" + productnum);
        }

        model.addAttribute("num", num);
        model.addAttribute("sum", sum);
        model.addAttribute("shopcard", shopcards);
        session.setAttribute("productnum", productnum);
        return "/before/shopcart";
    }


    /**
     * 将所有的购物车的东西写到/before/person/order页面中
     */
    @RequestMapping(value = "/ordershow", method = RequestMethod.GET)
    public String ordershow(Model model, HttpSession session) {

        String id = session.getAttribute("id").toString();
        //根据u_id查询出所有的产品信息
        List<Orders> orders = orderService.show(id);
        System.out.println("查出的记录总共有" + orders.size());
        //查出数据库中没有支付的商品payment_staus为0为没有支付
        //查出数据库中待发货的订单信息
        List<Orders> orders2 = orderService.show2(id);
        //查出数据库中待收货的订单信息
        List<Orders> orders3 = orderService.show3(id);
        List<Orders> orders1 = orderService.show1(id);
        model.addAttribute("orders1", orders1);
        model.addAttribute("orders", orders);
        model.addAttribute("orders2", orders2);
        model.addAttribute("orders3", orders3);
        return "/before/person/order";
    }

    /**
     * 该页面展示所有爬取到的数据对展示的数据进行排序等操作
     * */
    @RequestMapping(value = "/showall",method = RequestMethod.GET)
    public String showall(Model model,HttpSession session){
        List<ProductGet> products=productGetService.listall();
        model.addAttribute("product",products);
        return "/before/searchall";
    }

    @RequestMapping(value = "product_list", method = RequestMethod.GET)
    public String list() {
        return "back/product-list";
    }

    //导入excel表的显示记录
    @RequestMapping(value = "/product_listget", method = RequestMethod.GET)
    public String listget() {
        return "back/product-listget";
    }

    @RequestMapping("product_list2")
    public String list(Model model) {
        List<Product> products = productService.list();
        model.addAttribute("ps", products);
        return "back/product-list";
    }

    @RequestMapping(value = "product_listtest", method = RequestMethod.GET)
    @ResponseBody
    public List<Product> listall(Model model, Product product) {
        List<Product> products = productService.list();
        model.addAttribute("products", products);
        //return "back/product-list2";
        return products;
    }

    @RequestMapping(value = "product_delete", method = RequestMethod.GET)
    public String product_delete(@RequestParam("pId") String pId, Model model) {

        int delete = productService.delete(pId);
        return "back/product-list";
    }

    @RequestMapping(value="product_add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> product_add(Product product, Model model, HttpServletResponse response) {
        // int updated=productService.saveProduct(product);
        product.getDictionaryid();
        product.getProductName();
        product.getContent();
        product.getDazhe();
        product.getNum();
        product.getMoney();

        Map<String,String> map=new HashMap<String,String>();
        int update=productService.updatename(product);
        if(update>0)
        {

            map.put("result","success");

        }
        else
            map.put("result","fail");
        return map;
//        return "redirect:/product/product_list?dictionaryid="+product.getDictionaryid();
    }
    @RequestMapping(value = "imageedit", method = RequestMethod.POST)
    public String i(Product product, @RequestParam("file") MultipartFile multipartFile, Model model) throws IOException {
        String filename = multipartFile.getOriginalFilename();
        String sname = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID() + sname;
        String filepath = "E:/myFile/";
        product.setProductPic("/myFile/" + filename);
        multipartFile.transferTo(new File(filepath + filename));
        product.getpId();
        productService.updatename(product);
        //int updated=productService.saveProduct(product);
        return "redirect:/product/product_edit?pId=" + product.getpId();

    }

    @RequestMapping("product_edit")
    public String product_edit(@RequestParam("pId") String pId, Model model) {
        Product product = productService.getpId(pId);
        model.addAttribute("product", product);
        return "back/EditPage2";
    }

    @RequestMapping(value = "product_insert", method = RequestMethod.GET)
    public String product_insert(Product product) {
        productService.add(product);
        return "back/product-list";
    }

    @GetMapping("/api/searchproduct")
    @ResponseBody//需要返回json数据
    public SearchProductResponse searchUser(Integer pageNum, Integer pageSize, String keyword) {
        return productService.listUser(pageSize, pageNum, keyword);
    }
    @GetMapping("/api/searchproductget")
    @ResponseBody//需要返回json数据
    public SearchProductGetResponse searchUser1(Integer pageNum, Integer pageSize, String keyword) {
        return productGetService.list(pageNum,pageSize,keyword);
    }


}
